package br.com.roteador.rota;

import java.util.Date;
import java.util.List;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.roteador.motorista.Motorista;
import br.com.roteador.persistence.AbstractDAO;

@Named("rotaDAO")
public class RotaDAO extends AbstractDAO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4035111373214811122L;

	public RotaDAO(EntityManager manager) {
		this.manager = manager;
	}
	
	public RotaDAO (){}

	public Rota recuperaRotaPorMotoristaDataInicioFim(Date dataInicio, Date dataFim, Motorista motorista) {
		CriteriaBuilder qb = manager.getCriteriaBuilder();
		CriteriaQuery<Rota> cq = qb.createQuery(Rota.class);
		Root<Rota> tb = cq.from(Rota.class);
		Predicate eq3 = null;
		Predicate eq4 = null;
		Expression<Date> dtPrevIni = tb.get("dataInicio");
		Expression<Date> dtPrevFim = tb.get("dataFim");
		eq3 = qb.greaterThanOrEqualTo(dtPrevFim, dataFim);
		eq4 = qb.lessThanOrEqualTo(dtPrevIni, dataInicio);
		cq.select(tb);
		cq.where(qb.and(eq3, eq4), qb.equal(tb.get("motorista"), motorista));
		return (Rota) recuperaRegistro(montaQuery(cq));
	}

	public List<Rota> recuperaRotas() {
		CriteriaBuilder qb = manager.getCriteriaBuilder();
		CriteriaQuery<Rota> cq = qb.createQuery(Rota.class);
		Root<Rota> tb = cq.from(Rota.class);
		cq.select(tb);
		return (List<Rota>) recuperaLista(montaQuery(cq));
	}
	
	public Rota recuperaRotaAtualPorMotorista(Motorista motorista) {
		Date dataAtual = new Date();
		CriteriaBuilder qb = manager.getCriteriaBuilder();
		CriteriaQuery<Rota> cq = qb.createQuery(Rota.class);
		Root<Rota> tb = cq.from(Rota.class);
		Predicate eq3 = null;
		Predicate eq4 = null;
		Expression<Date> dtPrevIni = tb.get("dataInicio");
		Expression<Date> dtPrevFim = tb.get("dataFim");
		eq3 = qb.greaterThanOrEqualTo(dtPrevFim, dataAtual);
		eq4 = qb.lessThanOrEqualTo(dtPrevIni, dataAtual);
		cq.select(tb);
		cq.where(qb.and(eq3, eq4), qb.equal(tb.get("motorista"), motorista));
		return (Rota) recuperaRegistro(montaQuery(cq));
	}

}